package dao.impl;

import dao.MyUserDao;
import org.springframework.stereotype.Repository;
import pojo.MyUser;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Repository
public class MyUserDaoImpl implements MyUserDao {

    @Resource(name="dataSource")
    private DataSource dataSource;

    public int add(MyUser myUser) {
        String sql = "insert into my_users(id,uname,psd,age) values(?,?,?,?)";
        Connection conn = null;
        PreparedStatement pst = null;
        int m = 0;
        try {
            conn = dataSource.getConnection();
            pst = conn.prepareStatement(sql);
            pst.setString(1,myUser.getId());
            pst.setString(2,myUser.getUname());
            pst.setString(3,myUser.getPsd());
            pst.setInt(4,myUser.getAge());
            m = pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            close(conn,pst,null);
        }
        return m;
    }

    public MyUser get(String uname) {
       String sql = "select * from my_users where uname=?";
       Connection conn = null;
       PreparedStatement pst = null;
       ResultSet rs = null;
       MyUser myUser = null;
       int m = 0;
        try {
            conn = dataSource.getConnection();
            pst = conn.prepareStatement(sql);
            pst.setString(1,uname);
            rs = pst.executeQuery();
            if (rs.next()){
                myUser = new MyUser();
                myUser.setId(rs.getString("id"));
                myUser.setUname(rs.getString("uname"));
                myUser.setPsd(rs.getString("psd"));
                myUser.setAge(rs.getInt("age"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            close(conn,pst,rs);
        }
        return myUser;
    }

    private void close(Connection conn, PreparedStatement pst, ResultSet rs){
            try {
                if (conn!=null)
                    conn.close();
                if (pst!=null)
                    pst.close();
                if (rs!=null)
                    rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
    }
}
